<template>
  <div
    class="fixed top-[20%] left-[50%] translate-x-[-50%] w-[340px] h-[270px] text-sm bg-white dark:bg-zinc-800 rounded border border-zinc-200 dark:border-zinc-900 shadow-2xl"
  >
    <div class="flex items-center h-5 text-left px-1 mb-1">
      <span class="flex-grow dark:text-zinc-200">请完成安全验证</span>
      <m-svg-icon
        name="refresh"
        @click="onRefresh"
        fillClass="fill-zinc-900 dark:fill-zinc-200"
        class="w-2.5 h-2.5 p-0.5 rounded-sm duration-300 cursor-pointer hover:bg-zinc-200 dark:hover:bg-zinc-900"
      />
      <m-svg-icon
        name="close"
        @click="onClose"
        fillClass="fill-zinc-900 dark:fill-zinc-200"
        class="ml-0.5 w-2.5 h-2.5 p-0.5 rounded-sm duration-300 cursor-pointer hover:bg-zinc-200 dark:hover:bg-zinc-900"
      />
    </div>
    <!-- 人类行为验证 -->
    <div id="captcha"></div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import '@/vendor/SliderCaptcha/longbow.slidercaptcha.min.js'
import '@/vendor/SliderCaptcha/slidercaptcha.min.css'

import { getCaptcha } from '@/api/sys'
const emits = defineEmits(['captchaClose', 'captchaSuccess'])

// 使用模块
const Captcha = ref(null)
onMounted(() => {
  // 获取行为验证实例 在引入模块后 自动获取实例函数 sliderCaptcha
  Captcha.value = sliderCaptcha({
    // 渲染位置
    id: 'captcha',
    // 拼图成功回调
    onSuccess: (arr) => {
      getCaptcha({ behavior: arr }).then((res) => {
        if (res.code == 200) {
          emits('captchaSuccess')
        }
      })
    },
    // 拼图失败回调
    onFail: () => {
      // console.log('失败')
      return false
    },
    // 默认验证方法
    verify: (arr) => {
      // 也可以在这里获取滑块轨迹
      return true
    }
  })
})

// 重置事件
const onRefresh = () => {
  Captcha.value.reset()
}

// 关闭事件
const onClose = () => {
  emits('captchaClose')
}
</script>
<style scoped lang="scss"></style>
